package com.example.demo.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-27
 * Time:14:10
 */
@ControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice {

    // 返回true表示返回数据之前对数据进行重写，即进入beforeBodyWrite方法
    // 返回false表示对结果不进行任何处理，直接返回
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("state", 1);
        result.put("data", o);
        result.put("msg", "");
        return result;
    }
}
